package phi.engine.actors
{
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.b2Body;
	import Box2D.Dynamics.b2BodyDef;

	import phi.engine.core.GameTime;
	import phi.engine.events.ActorEvent;
	import phi.engine.utils.PhiMathUtil;

	public class InteractiveActor extends VisualActor 
		implements IInteractiveActor
	{
		protected var _body :b2Body = null;

		public function InteractiveActor ( options :ActorOptions = null )
		{
			super( options );
		}

		// -----------------------------------------------------------------------------
		// Public Get/Set funcitons
		// -----------------------------------------------------------------------------
		
		public function get body () :b2Body
		{
			return _body;
		}

		public function set body ( value :b2Body ) :void
		{
			_body = value;
			setBodyOptions();
		}

		// -----------------------------------------------------------------------------
		// Public funcitons
		// -----------------------------------------------------------------------------
		
		override public function update ( gameTime :GameTime ) :void
		{
			super.update( gameTime );
			
			// If we have a body then
			// update according to him
			if ( body != null )
			{
				x = PhiMathUtil.metersToPixels( body.GetPosition().x );
				y = PhiMathUtil.metersToPixels( body.GetPosition().y );
				rotation = PhiMathUtil.toDegree( body.GetAngle());
			}
		}

		override public function destroy():void
		{
			super.destroy();
			destroyBody();
		}
		
		// -----------------------------------------------------------------------------
		// Protected funcitons
		// -----------------------------------------------------------------------------

		protected function createBody () :void
		{
			body = engine.game.world.CreateBody( new b2BodyDef());
		}

		protected function destroyBody () :void
		{
			engine.game.world.DestroyBody( body );
		}

		protected function setBodyOptions () :void
		{
			body.SetPosition( new b2Vec2( options.startPositionToMeters.x, options.startPositionToMeters.y ));
			body.SetAngle( PhiMathUtil.toRadians( options.startAngle ));
			body.SetLinearVelocity( options.velocity.Copy());
			body.SetType( options.bodyType );
			body.SetFixedRotation( options.fixRotation );
		}

		override protected function optionsChangeHandler ( event :ActorEvent ) :void
		{
			super.optionsChangeHandler( event );
			
			if( body == null )
				createBody();
		}
	}
}